package com.lanou.tipsy.fragment.songsList;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.lanou.tipsy.R;
import com.lanou.tipsy.adapter.songList.SongListPopupWindow;
import com.lanou.tipsy.adapter.songList.SongsListsAdapter;
import com.lanou.tipsy.base.BaseFragment;
import com.lanou.tipsy.base.Constants;
import com.lanou.tipsy.entity.songList.songslist.ChildrenEntity;
import com.lanou.tipsy.entity.songList.songslist.RankDataEntity;
import com.lanou.tipsy.entity.songList.songslist.SongList;
import com.lanou.tipsy.entity.songList.songslist.SongListData;
import com.lanou.tipsy.entity.songList.songslist.SongRank;
import com.lanou.tipsy.tools.volley.ResponseErrorListener;
import com.lanou.tipsy.tools.volley.VolleySingleton;

import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;

/**
 * Created by dllo on 15/10/20.
 * <p/>
 * EE
 * 歌单 页面
 */

public class SongsListsFragment extends BaseFragment {
    public static final String TAG = "SongsListsFragment";
    private GridView gridView;
    private SongsListsAdapter songsListsAdapter;
    private VolleySingleton volleySingleton;
    private ResponseErrorListener errorListener;
    private ArrayList<SongListData> data;//实体类集合
    private SongListData songListData;//实体类
    private TextView allListTv;//全部分类(按钮)
    private String tag, tagId, newUrl;//歌单分类标签,ID,刷新页面的URL
    private SongListPopupWindow popupWindow;//弹出菜单
    private ArrayList<RankDataEntity> menuData;//实体类
    private RequestQueue requestQueue;//请求队列
    private TextView allSongListBt;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fr_songs_lists, null);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView(getView());
    }

    private void initView(View view) {
        //初始化各种组件
        gridView = (GridView) view.findViewById(R.id.gridViewSongsLists);
        allSongListBt = (TextView) view.findViewById(R.id.allSongListBt);
        volleySingleton = VolleySingleton.getInstance();
        errorListener = new ResponseErrorListener();

        //歌单GridView点击简体,点击并跳转,向下一个页面传递所需数据
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Log.i("test onclick", "无点击事件");
                if (parent == gridView) {
                    //从拉取的数据中获取歌单ID
                    int songid = data.get(position).get_id();
                    String songidcontent = songid + "";
                    //跳转fragment
                    FragmentManager manager = getActivity().getSupportFragmentManager();
                    SongsListsContentFragment fragment = new SongsListsContentFragment();
                    Bundle bundle = new Bundle();
                    bundle.putString("songid", songidcontent);
                    fragment.setArguments(bundle);
                    FragmentTransaction transaction = manager.beginTransaction();
                    transaction.addToBackStack(null);
                    transaction.replace(R.id.fl_main, fragment);
                    transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
                    transaction.commit();
                }
            }
        });

        //把文字控件添加监听，点击弹出自定义窗口
        allSongListBt.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                //实例化SelectPicPopupWindow
                popupWindow = new SongListPopupWindow(getActivity(), itemsOnClick, onClick, menuData);
                //显示窗口,设置layout在PopupWindow中显示的位置
                popupWindow.showAtLocation(v, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
                //销毁窗口的时候,背景回复正常
                popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        Log.i("test", TAG + "弹出窗口销毁" + "dismiss");
                        WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
                        lp.alpha = 1f;
                        getActivity().getWindow().setAttributes(lp);
                    }
                });
            }
        });

        initNetWork();
        songListNetWork();
    }

    /**
     * 网络拉取
     */
    private void initNetWork() {
        //requestQueue = Volley.newRequestQueue(getActivity());
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Constants.SONG_LIST_DETAIL/*url待定*/, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                if (response != null) {
                    Log.i("test", TAG + "歌单首页" + response + "");
                    Gson gson = new Gson();
                    String str = response.toString();
                    songListData = new SongListData();
                    SongList songList = gson.fromJson(str, SongList.class);
                    data = songList.getData();
                    songsListsAdapter = new SongsListsAdapter(getActivity(), data);
                    gridView.setAdapter(songsListsAdapter);

                }
            }
        }, errorListener);
        //requestQueue.add(jsonObjectRequest);
        volleySingleton.addQueue(jsonObjectRequest, TAG);
    }

    private void songListNetWork() {
        //String listUrl = "http://api.dongting.com/song/tag/songlist";
        requestQueue = Volley.newRequestQueue(getActivity());
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Constants.SONG_LIST_MENU, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                Log.i("testMenu", TAG + "歌单信息" + response + "");
                if (response != null) {
                    Gson gson = new Gson();
                    String str = response.toString();
                    SongRank songRank = gson.fromJson(str, SongRank.class);
                    menuData = songRank.getData();
                }
            }
        }, errorListener);
        requestQueue.add(jsonObjectRequest);
        //volleySingleton.addQueue(jsonObjectRequest, TAG);
    }

    private AdapterView.OnItemClickListener itemsOnClick = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            popupWindow.dismiss();
            ChildrenEntity childrenEntity = (ChildrenEntity) parent.getItemAtPosition(position);
            //选择歌单某个分类后,返回给菜单按钮,并重新设置文字
            if (childrenEntity != null) {
                String tag = childrenEntity.getTag();
                int intTtagId = childrenEntity.getTagID();
                String tagId = intTtagId + "";
                Log.i("test", TAG + tag + " " + tagId);
                if (tag != null && tag != "") {
                    allSongListBt.setText(tag);
                    refreshData(tag);
                }
            } else {
                //allSongListBt.setText("全部分类");
                //initNetWork();
                Log.i("SongListFragment","无效点击");
            }
        }
    };

    private View.OnClickListener onClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            popupWindow.dismiss();
            switch (v.getId()) {
                case R.id.allListMenuTv:
                    Log.i("test", TAG + "全部:>>>>>" + "点击按钮");
                    allSongListBt.setText("全部分类");
                    initNetWork();
                    break;
            }
        }
    };

    //选择菜单后,刷新当前页面的方法
    private void refreshData(String tag) {
        try {
            //将选择的分类转化成UTF-8格式,并且拼接URL
            String tvTag = URLEncoder.encode(tag, "utf-8");
            newUrl = Constants.SONG_LIST_MOSAIC_FIRST + tvTag + Constants.SONG_LIST_MOSAIC_SECOEND;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //重新拉取
        //requestQueue = Volley.newRequestQueue(getActivity());
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(newUrl/*url待定*/, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                if (response != null) {
                    Gson gson = new Gson();
                    String str = response.toString();
                    songListData = new SongListData();
                    SongList songList = gson.fromJson(str, SongList.class);
                    data = songList.getData();
                    //songsListsAdapter.refreshData(data);
                    songsListsAdapter = new SongsListsAdapter(getActivity(), data);
                    gridView.setAdapter(songsListsAdapter);
                }
            }
        }, errorListener);
        //requestQueue.add(jsonObjectRequest);
        volleySingleton.addQueue(jsonObjectRequest, TAG);
    }


}